#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @License: Copyright © 2019 代鹏. All rights reserved.
# @Author: 代鹏
# @Contact: 272481080@qq.com
# @File: restfull.py
# @Date: 2019/7/1
# @Software：kk
# @description :
from app import app,api
from functools import wraps
from flask import jsonify,Flask,request, current_app
import time, datetime, json
from flask_restful import reqparse, abort, Api, Resource
from elasticsearch import Elasticsearch
from app.server import cu_mongodb_conn
from flask import make_response


parser = reqparse.RequestParser()
parser.add_argument('task')
parser.add_argument('callback')

app.config.from_object('config')
host = app.config.get('ES_HOST')
port = app.config.get('ES_PORT')
es = Elasticsearch([{'host': host, 'port': port}])
# TODOS = {
#     'todo1': {'task': 'build an API'},
#     'todo2': {'task': '哈哈哈'},
#     'todo3': {'task': 'profit!'},
# }
TODOS = {
    "goods": [
        { "price": "69.9", "title": "德芙", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t3688/270/776223567/128582/fa074fb3/58170f6dN6b9a12bf.jpg!q50.jpg.webp" },
        { "price": "63", "title": "费列罗", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t613/100/1264998035/221234/1a29d51f/54c34525Nb4f6581c.jpg!q50.jpg.webp"},
        { "price": "29.9", "title": "大米", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t1258/40/17387560/108696/aced445f/54e011deN3ae867ae.jpg!q50.jpg.webp"},
        { "price": "54.9", "title": "安慕希", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t2734/15/680373407/215934/3abaa748/572057daNc09b5da7.jpg!q50.jpg.webp"},
        { "price": "58", "title": "金典", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t2482/145/1424008556/91991/d62f5454/569f47a2N3f763060.jpg!q50.jpg.webp"},
        { "price": "60", "title": "味可滋", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t2368/3/874563950/70786/7b5e8edd/563074c8N4d535db4.jpg!q50.jpg.webp" },
        { "price": "248.00", "title": "泸州老窖", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t283/166/1424018055/189580/7c0792b7/543b4958N05fa2feb.jpg!q50.jpg.webp"},
        { "price": "328.8", "title": "剑南春", "img": "http://m.360buyimg.com/babel/s350x350_g15/M05/1A/0A/rBEhWlNeLAwIAAAAAAHyok3PZY0AAMl8gO8My0AAfK6307.jpg!q50.jpg.webp"},
        { "price": "49.00", "title": "蓝莓", "img": "http://m.360buyimg.com/babel/s211x211_jfs/t2332/148/2952098628/94387/e64654e2/56f8d76aNb088c2ab.jpg!q50.jpg.webp" },
        { "price": "68", "title": "芒果", "img": "http://m.360buyimg.com/n0/jfs/t3709/334/1378702984/206759/5c100ab5/58253588Naaa05c5c.jpg!q70.jpg"}
    ]
}
create_wiki_id = lambda: 'wiki_' + str(round(time.time()*1000))
def support_jsonp(f):
    """Wraps JSONified output for JSONP"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        callback = request.args.get('callback', False)
        if callback:
            # content = str(callback) + '(' + str(f(*args,**kwargs).data) + ')'
            content = str(callback) + '(' + str(f(*args,**kwargs)) + ')'
            return current_app.response_class(content, mimetype='application/javascript')
        else:
            return f(*args, **kwargs)
    return decorated_function

def abort_if_todo_doesnt_exist(todo_id):
    if todo_id not in TODOS:
        abort(404, message="Todo {} doesn't exist".format(todo_id))

 #Todo
# shows a single todo item and lets you delete a todo item
class Todo(Resource):
    @support_jsonp
    def get(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        # return TODOS[todo_id]
        res = cu_mongodb_conn.find_one('wiki_content', {})
        # for k in res:
        #     print(k, ':', res[k])
        resp = dict()
        resp['status'] = 0
        resp['data'] = res['content']
        return resp

    def post(self):
        args = parser.parse_args()
        # todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        # todo_id = 'todo%i' % todo_id
        # TODOS[todo_id] = {'task': args['task']}
        print(args)
        return TODOS["goods"], 201

    def delete(self, todo_id):
        abort_if_todo_doesnt_exist(todo_id)
        del TODOS[todo_id]
        return '', 204

    def put(self, todo_id):
        args = parser.parse_args()
        task = {'task': args['task']}
        TODOS[todo_id] = task
        return task, 201


# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
    @support_jsonp
    def get(self):
        args = parser.parse_args()
        cb = args['callback']
        # get获取
        res = (es.search(index='monitor',doc_type='status',body={"query":{"match_all":{}}}))['hits']
        # res = get_es_count('3000m',["rollIn", "recharge"])
        # return TODOS
        # return cb+"("+json.dumps(TODOS)+")"
        return jsonify(res)

    def post(self):
        args = parser.parse_args()
        todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
        todo_id = 'todo%i' % todo_id
        TODOS[todo_id] = {'task': args['task']}
        return TODOS[todo_id], 201


@app.route('/saveWiki', methods=['GET', 'POST'])
def save_wiki():
    data = request.get_json()
    print(data)
    wiki = dict()
    wiki['_id'] = data['id'] if data['id'] is None else create_wiki_id()
    wiki['content'] = data['data']
    wiki['title'] = data['title']
    wiki_info = dict()
    have_wiki = cu_mongodb_conn.find_one('wiki_info',{'_id': wiki['_id']})
    if have_wiki is None:
        wiki_info['create_time'] = datetime.datetime.utcnow()
    wiki_info['last_time'] = datetime.datetime.utcnow()
    cu_mongodb_conn.update_one('wiki_content', {'_id': wiki['_id']}, {'$set': wiki}, True)
    cu_mongodb_conn.update_one('wiki_info', {'_id': wiki['_id']}, {'$set': wiki_info}, True)
    return add_headers(str({'status': 0, 'data': wiki['_id']})), 201


@app.route('/getWikiList/<pageNum>', methods=['GET', 'POST'])
def get_wiki_list(pageNum):
    pageNum = 1 if pageNum is None else int(pageNum)
    limit = 10
    res = cu_mongodb_conn.find_many('wiki_info', {}, 'last_time', -1, limit, (pageNum - 1) * limit)
    rows = []
    for k in res:
        row = dict()
        # for key, value in k.items():
        #     row[key] = value
        row['id'] = k['_id']
        row['last_time'] = k['last_time'].__format__('%Y-%m-%d')
        rows.append(row)
    return add_headers(str({'status': 0, 'data': rows}))


# 判断是否是OPTIONS请求
@app.before_request
def is_options():
    if request.method == 'OPTIONS':
        rst = make_response("ok")
        rst.headers['Access-Control-Allow-Origin'] = '*'
        # rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
        allow_headers = "Referer,Accept,Origin,User-Agent,Content-Type"
        rst.headers['Access-Control-Allow-Headers'] = allow_headers
        abort(rst)
    else:
        pass


# 添加跨域header
def add_headers(massage):
    rst = make_response(massage)
    rst.headers['Access-Control-Allow-Origin'] = '*'
    # rst.headers['Access-Control-Allow-Methods'] = 'PUT,GET,POST,DELETE'
    allow_headers = "Referer,Accept,Origin,User-Agent,Content-Type"
    rst.headers['Access-Control-Allow-Headers'] = allow_headers
    return rst



##
##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')